﻿using System;
using System.Diagnostics;
using System.Linq;
using Cav;
using Cav.WinForm.BaseClases;
using Nefela.BusinessLogic;
using Nefela.CommonTypes;

namespace Nefela.UI
{
    public partial class ucCustomerCards : UserControlBase
    {
        public ucCustomerCards()
        {
            InitializeComponent();
        }

        private CustomerCardBL ccdrBL;
        private SettingsBL setBL;

        public override void RefreshControl()
        {
            base.RefreshControl();

            ucCustomerCards_Load(null, null);
        }
        private void ucCustomerCards_Load(object sender, EventArgs e)
        {
            if (this.IsDesignMode)
                return;

            ccdrBL = new CustomerCardBL();
            ccdrBL.LoadCards();

            dgvFiedsCard.AutoGenerateColumns = false;

            lbCards.DataSource = ccdrBL.ModelCards;
            lbCards.DisplayMember = "Name";
            lbCards.ClearSelected();

            setBL = (SettingsBL)this.BusinessLogic;
        }

        private void btCardAdd_Click(object sender, EventArgs e)
        {
            if (setBL.ModelPackegeDocs.CardCustomer.Count == 0 ||
                setBL.ModelPackegeDocs.TemplatesDocs.Count == 0)
            {
                Dialogs.InformationF(this, "Для добавления карточек необходимо настроить поля карочек и шаблоны документов");
                return;
            }


            String NewName = "Новая карточка " + DateTime.Now.ToString();
            Boolean nameExist;

            do
            {
                NewName = Dialogs.InputBox(
                Owner: this,
                Title: "Наименование карточки",
                DescriptionText: @"Введите наименование карточки",
                DefautText: NewName,
                MaxLength: 80)
                .Trim2();

                if (NewName.IsNullOrWhiteSpace())
                    return;

                nameExist = ccdrBL.ModelCards.Any(x => x.Name == NewName);

                if (nameExist)
                    Dialogs.ErrorF(this, "Карточка с таким наименованием уже есть");

            } while (nameExist);

            ccdrBL.ModelCards.Add(new CustomerCardType() { Name = NewName });

            ccdrBL.Save();
        }

        private void lbCards_SelectedIndexChanged(object sender, EventArgs e)
        {
            btCardDel.Enabled =
                btCardEdit.Enabled = lbCards.SelectedItem != null;

            dgvFiedsCard.AutoGenerateColumns = false;

            if (lbCards.SelectedItem != null)
                dgvFiedsCard.DataSource = ((CustomerCardType)lbCards.SelectedItem).Fields.Where(x => !x.FieldCardCustomer.UserInput).ToList();
            else dgvFiedsCard.DataSource = null;

            dgvFiedsCard.AutoGenerateColumns = false;
        }

        private void btCardDel_Click(object sender, EventArgs e)
        {
            var card = lbCards.SelectedItem as CustomerCardType;

            if (card == null)
                return;

            if (!Dialogs.QuestionOKCancelF(this, String.Format("Удалить карточку '{0}'?", card.Name)))
                return;

            ccdrBL.RemoveCard(card);

            ccdrBL.Save();

            lbCards.ClearSelected();
            dgvFiedsCard.DataSource = null;
        }

        private void btCardEdit_Click(object sender, EventArgs e)
        {
            var card = lbCards.SelectedItem as CustomerCardType;

            if (card == null)
                return;

            String NewName = card.Name;
            Boolean nameExist;

            do
            {
                NewName = Dialogs.InputBox(
                Owner: this,
                Title: "Наименование карточки",
                DescriptionText: @"Введите наименование карточки",
                DefautText: NewName,
                MaxLength: 80)
                .Trim2();

                if (NewName.IsNullOrWhiteSpace())
                    return;

                nameExist = ccdrBL.ModelCards.Any(x => x.Name == NewName);

                if (nameExist)
                    Dialogs.ErrorF(this, "Карточка с таким наименованием уже есть");

            } while (nameExist);

            card.Name = NewName;

            ccdrBL.Save();
        }

        private void dgvFiedsCard_CellStateChanged(object sender, System.Windows.Forms.DataGridViewCellStateChangedEventArgs e)
        {
            ccdrBL.Save();
        }

        private void ucCustomerCards_HelpRequested(object sender, System.Windows.Forms.HelpEventArgs hlpevent)
        {
            Process.Start("https://goo.gl/XrWaVM");
        }



    }
}
